package com.fh.alipay.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fh.alipay.annotation.Authorize;
import com.fh.alipay.po.User;
import com.fh.alipay.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @FileName: LoginHandlerInterceptor
 * @Author: fh
 * @Date: 2021/12/14 16:50
 * @Description: 登录拦截
 * @Version: 1.0
 */
@Slf4j
public class LoginHandlerInterceptor implements HandlerInterceptor {


    @Autowired
    private IUserService userService;

    /**
     * 请求之前被调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        //检查有没有需要用户权限的注解
        //如果有注解Authorize，就需要验证token
        if (method.isAnnotationPresent(Authorize.class)) {
            Authorize userLoginToken = method.getAnnotation(Authorize.class);
            if (userLoginToken.required()) {
                // 从 http 请求头中取出 token
                String token = request.getHeader("Authorization");
//        log.info("用户token:{}", token);
                // 执行认证
                if (token == null) {
                    returnJson(response, "无token，请重新登录");
                    return false;
                }
                // 获取 token 中的 userName
                String userName;
                try {
                    // 获取 userName
                    userName = JWT.decode(token).getKeyId();
                    // 添加request参数，用于传递 userName
                    request.setAttribute("currentUser", userName);
                    // 根据 userName 查询用户信息
                    User user = userService.getOne(Wrappers.lambdaQuery(User.class)
                            .select(User::getUsername, User::getPassword, User::getUserType)
                            .eq(User::getUsername, userName));
                    if (user == null) {
                        returnJson(response, "用户不存在，请重新登录");
                        return false;
                    }

                    try {
                        String loginName = JWT.decode(token).getClaim("loginName").as(String.class);
                        // 添加request参数，用于传递 userName
                        request.setAttribute("loginName", loginName);
                    } catch (Exception ignored) {
                    }

                    // 验证 密码
                    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                    try {
                        jwtVerifier.verify(token);
                    } catch (JWTVerificationException e) {
                        returnJson(response, "密码验证失败");
                        return false;
                    }
                } catch (JWTDecodeException j) {
                    returnJson(response, "解密token失败");
                    return false;
                }
//        log.info("token校验成功");
                return true;

            }
        }
        return true;
    }

    /**
     * 返回json
     *
     * @param response
     */
    private void returnJson(HttpServletResponse response, String msg) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print("{\"msg\":\"" + msg + "\"}");

        } catch (IOException e) {
            log.error("returnJson error：" + e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 请求执行完成后，生成视图之前执行
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求后被调用
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}